<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useMessage, NButton, NGrid, NGi, NSpin, NFlex } from 'naive-ui'
import { ProCard, createProForm, ProInput, ProCheckbox } from 'pro-naive-ui'
import ConfigProvider from '../../ConfigProvider.vue'
import { zhCN } from 'pro-naive-ui'

import { fetchGetUdiConfig, fetchSaveConfig } from '@/service/api/udi'

interface BackendFieldConfig {
  label: string;
  value: string | boolean;
}

interface BackendUDIData {
  unifiedSocialCreditCode: BackendFieldConfig;
  registrantName: BackendFieldConfig;
  registrantCertificateNo: BackendFieldConfig;
  showWarranty: BackendFieldConfig;
}

interface FrontendFormItem {
  field: keyof BackendUDIData;
  label: string;
  component: 'input' | 'checkbox';
  placeholder: string;
}

interface FormValues {
  unifiedSocialCreditCode: string;
  registrantName: string;
  registrantCertificateNo: string;
  showWarranty: boolean;
}

// 初始化状态
const message = useMessage()
const isLoading = ref(true)
const submitting = ref(false)

// 存储前端用的表单项配置和表单值
const formConfig = ref<{
  items: FrontendFormItem[];
  values: FormValues;
}>({
  items: [],
  values: {
    unifiedSocialCreditCode: '',
    registrantName: '',
    registrantCertificateNo: '',
    showWarranty: false
  }
})

// 创建表单时指定 FormValues 类型，避免 values 类型未知
const form = createProForm<FormValues>({
  initialValues: {
    unifiedSocialCreditCode: '',
    registrantName: '',
    registrantCertificateNo: '',
    showWarranty: false
  },
  onSubmit: async (values: FormValues) => { // 显式指定 values 类型
    try {
      submitting.value = true
      await fetchSaveConfig(values)
      message.success('保存成功')
    } catch (e) {
      message.error('保存失败')
    } finally {
      submitting.value = false
    }
  },
  onReset: () => {
    loadData()
  }
})

async function loadData() {
  isLoading.value = true
  try {
    // 给返回的 data 指定 BackendUDIData 类型，避免 data 是 any
    const { data } = await fetchGetUdiConfig() as { data: BackendUDIData };

    // 解析后端数据：生成表单项 + 提取表单值
    const items: FrontendFormItem[] = []
    const values: FormValues = {
      unifiedSocialCreditCode: '',
      registrantName: '',
      registrantCertificateNo: '',
      showWarranty: false
    }

    for (const field of Object.keys(data) as (keyof BackendUDIData)[]) {
      const config = data[field];

      // 生成表单项配置
      items.push({
        field,
        label: config.label,
        // 判断组件类型：showWarranty 是复选框，其他是输入框
        component: field === 'showWarranty' ? 'checkbox' : 'input',
        placeholder: `请输入${config.label}`
      })

      // 提取表单值（根据组件类型做类型转换，避免类型不匹配）
      if (field === 'showWarranty') {
        values[field] = config.value as boolean; // 复选框值是 boolean
      } else {
        values[field] = config.value as string; // 输入框值是 string
      }
    }

    // 更新表单配置和初始值
    formConfig.value = { items, values }
    form.values.value = values
  } finally {
    isLoading.value = false
  }
}

onMounted(loadData)
</script>

<template>
  <ConfigProvider :locale="zhCN">
    <ProForm :form="form" :loading="submitting">
      <ProCard title="UDI配置" :show-collapse="false">
        <template #header-extra>
          <NFlex gap="12px">
            <NButton attr-type="reset" :disabled="isLoading">重置</NButton>
            <NButton type="primary" attr-type="submit" :loading="submitting">保存配置</NButton>
          </NFlex>
        </template>

        <NSpin :show="isLoading" size="medium" style="min-height: 200px;">
          <NGrid cols="1" :y-gap="4">
            <!-- 遍历动态生成的表单项 -->
            <NGi v-for="item in formConfig.items" :key="item.field" class="form-item">
              <p class="form-label">{{ item.label }}</p>

              <!-- 输入框 -->
              <ProInput v-if="item.component === 'input'" :path="item.field" class="form-input"
                :field-props="{ placeholder: item.placeholder }" />

            </NGi>
          </NGrid>
        </NSpin>
      </ProCard>
    </ProForm>
  </ConfigProvider>
</template>

<style scoped>
.form-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 4px 0;
  min-height: 32px;
}

.form-label {
  margin: 0;
  width: 200px;
  line-height: 32px;
  font-size: 14px;
  color: #333;
}

.form-input {
  flex: 1;
  width: 100%;
  max-width: 500px;
}
</style>
